# 创建数据库引擎
from typing import Annotated
from fastapi import Depends
from sqlalchemy import event, text, column
from sqlalchemy.orm import ORMExecuteState
from sqlmodel import SQLModel, create_engine, Session

from src.base.context import tenant_var, data_scope_var

MYSQL_URL = "mysql+pymysql://root:123456@127.0.0.1/fin_tax_analysis?charset=utf8mb4"

# echo=True会在控制台输出执行的SQL语句，方便调试
# check_same_thread=False是SQLite在多线程环境下的必要配置
engine = create_engine(MYSQL_URL, echo=True)


# engine = create_engine(app_config['datasource']['url'], echo=app_config['datasource']['sql-log'])
# 创建会话，并把当前引擎绑定给该对话
# SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine, expire_on_commit=True)


def create_db_and_tables():
    SQLModel.metadata.create_all(engine)


# 创建会话本地化
def get_session():
    with Session(engine) as session:
        yield session


mysqlClient = Session(engine)

mysqlClientDep = Annotated[Session, Depends(get_session)]


@event.listens_for(Session, "do_orm_execute", retval=True)
def apply_dept_filter(execute_state: ORMExecuteState):
    if not execute_state.is_select:
        return
    data_scope_sql_handle(execute_state)
    tenant_sql_handle(execute_state)


def tenant_sql_handle(execute_state):
    is_tenant = hasattr(execute_state.bind_mapper.class_, "tenant_id")
    tenant_dict = tenant_var.get()
    if tenant_dict and is_tenant:
        tenant_table_alias = tenant_dict['tenant_table_alias']
        tenant_id_alias = tenant_dict['tenant_id_alias']
        tenant_id_value = tenant_dict['tenant_id_value']
        execute_state.statement = execute_state.statement.where(
            text(f"{tenant_table_alias}.{tenant_id_alias} = {tenant_id_value}"))


def data_scope_sql_handle(execute_state):
    data_scope_dict = data_scope_var.get()
    if data_scope_dict:
        dept_table_alias = data_scope_dict['dept_table_alias']
        dept_id_alias = data_scope_dict['dept_id_alias']
        user_table_alias = data_scope_dict['user_table_alias']
        user_id_alias = data_scope_dict['user_id_alias']
        user_id_values = data_scope_dict["user_id_values"]
        dept_id_values = data_scope_dict["dept_id_values"]

        dept_where = None
        user_where = None
        if dept_id_values and len(dept_id_values) > 0:
            dept_where = f"{dept_table_alias}.{dept_id_alias} in ({', '.join(map(str, dept_id_values))})"
        if user_id_values and len(user_id_values) > 0:
            user_where = f"{user_table_alias}.{user_id_alias} in ({', '.join(map(str, user_id_values))})"
        data_scope_sql = None
        if dept_where and user_where:
            data_scope_sql = f" ( {dept_where}  OR {user_where} )"
        elif dept_where:
            data_scope_sql = f" {dept_where}"
        elif user_where:
            data_scope_sql = f" {user_where}"
        if data_scope_sql:
            execute_state.statement = execute_state.statement.where(text(data_scope_sql))


# ================== redis ===============================

import redis

REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379

# 创建一个全局的Redis连接池
redis_pool = redis.ConnectionPool(host=REDIS_HOST, port=REDIS_PORT, db=0, decode_responses=True)
redisClient = redis.Redis(connection_pool=redis_pool)
